//
//  Toast.swift
//  Runner
//
//  Created by 麻再挺 on 2019/3/25.
//  Copyright © 2019 The Chromium Authors. All rights reserved.
//

import UIKit

// 弹窗
class ToastView: NSObject {
    
    // 单例
    static let instance: ToastView = ToastView()
    // 获取窗口对象
    var windows = UIApplication.shared.windows
    // 键盘视图
    let rv = UIApplication.shared.keyWindow?.subviews.first as UIView!
    // 获取屏幕宽高
    let windowFrame = UIScreen.main.bounds
    // 显示弹窗
    // @param content 显示内容
    // @param duration 显示时长， 默认为1.5s
    func showToast(content: String, duration: CFTimeInterval = 1.5) {
        // 清除所有弹窗
        clear()
        // 创建 Toast 视图
        let contentView = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 50))
        // 设置字体大小
        contentView.font = UIFont.systemFont(ofSize: 13)
        // 设置字体颜色
        contentView.textColor = UIColor.white
        // 设置内容
        contentView.text = content
        // 设置对齐方式
        contentView.textAlignment = NSTextAlignment.center
        
        // 创建 Toast 父布局
        let containerView = UIView()
        // 设置圆角
        containerView.layer.cornerRadius = 10
        // 设置背景颜色
        containerView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7)
        
        // 将 Toast 视图 添加到 Toast 父布局中
        containerView.addSubview(contentView)
        
        let frame = CGRect(x: 0, y: 0, width: 300, height: 50)
        let window = UIWindow()
        window.backgroundColor = UIColor.clear
        window.frame = frame
        containerView.frame = frame
        window.windowLevel = UIWindowLevelAlert
        window.center = CGPoint(x: windowFrame.maxX * 0.5, y: windowFrame.maxY * 0.8)
//        window.center = CGPoint(x: rv?.center.x, y: rv?.center.y * 16 / 10)
        window.isHidden = false
        window.addSubview(containerView)
        
        windows.append(window)
        
        containerView.layer.add(AnimationUtil.getToastAnimation(duration: duration), forKey: "animation")
        
        
//        perform(#selector(removeToast(_:)), with: window, afterDelay: duration)
        
        DispatchQueue.main.asyncAfter(deadline: .now() + duration, execute:{
            self.removeToast(sender: window)
        })
    }
    
    // 移除当前所有弹窗
    func removeToast(sender: AnyObject) {
        if let window = sender as? UIWindow {
            if let index = windows.firstIndex(of: window) {
                // 移除对应 window
                windows.remove(at: index)
            }
        } else {
            print("can not find the window")
        }
    }
    
    // 清除所有弹窗
    func clear() {
        // 取消之前的所有请求
        NSObject.cancelPreviousPerformRequests(withTarget: self)
        // 移除全部
        windows.removeAll(keepingCapacity: false)
    }
}
